package com.juzhi.dvrapp.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.juzhi.dvrapp.R;
import com.juzhi.dvrapp.bean.Device;
import com.juzhi.dvrapp.bean.DeviceUser;
import com.juzhi.dvrapp.callback.DialogCallback;
import com.juzhi.dvrapp.bean.LzyResponse;
import com.juzhi.dvrapp.manager.DeviceManager;
import com.juzhi.dvrapp.utils.Config;
import com.juzhi.dvrapp.utils.T;
import com.juzhi.dvrapp.utils.Urls;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

public class DeviceEditActivity extends BaseAcitivity {


    @BindView(R.id.activity_edit_device_name)
    EditText mEditDeviceName;
    @BindView(R.id.activity_edit_device_ssid)
    EditText mEditSsid;
    @BindView(R.id.activity_edit_device_username)
    EditText mEditUserName;
    @BindView(R.id.activity_edit_device_password)
    EditText mEditPwd;
    @BindView(R.id.activity_edit_input_device_showpwd)
    Button mShowPwdBtn;
    private DeviceManager deviceManager;
    private Device device;

    private boolean isClickShowPwd = false;
    private AlertDialog alertDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_device_edit;
    }

    @Override
    protected void initView() {
        initHeaderView();
        setTitleText(getResources().getString(R.string.string_edit_device));
        hideFunction();

        String ssid = getIntent().getStringExtra(Config.SSID);
        deviceManager = DeviceManager.getDeviceManager(this);
        device = deviceManager.getDevice(ssid);

        if (device != null) {
            mEditDeviceName.setText(device.getDeviceModel().getDeviceName());
            mEditSsid.setText(device.getDeviceModel().getSsid());
        }
    }

    @OnClick({R.id.activity_edit_input_device_showpwd, R.id.activity_edit_device_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_edit_input_device_showpwd:
                showPwd();
                break;
            case R.id.activity_edit_device_btn:
                commitDevice(view);
                break;
        }
    }

    private void commitDevice(View view) {

            String deviceName = mEditDeviceName.getText().toString().trim();
            String userName = mEditUserName.getText().toString().trim();
            String password = mEditPwd.getText().toString().trim();

            String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(userName);
            Matcher m1 = p.matcher(password);
            if (m.find() || m1.find()) {
                T.showShort(getResources().getString(R.string.user_pwd_no_show));
                return;
            }


            if (TextUtils.isEmpty(deviceName)) {
                T.showShort(getResources().getString(R.string.input_camera_name));
                return;
            } else if (TextUtils.isEmpty(userName)) {
                T.showShort(getResources().getString(R.string.input_camera_username));
                return;
            } else if (TextUtils.isEmpty(password)) {
                T.showShort(getResources().getString(R.string.input_camera_password));
                return;
            }

            loginHttpRequest(view,userName,password);
    }

    private void loginHttpRequest(View view, final String userName, final String password) {
        OkGo.<LzyResponse<DeviceUser>>post(Urls.URL_DEVICELOGIN)
                .tag(DeviceEditActivity.this)
                .params(Config.DEVICEID, device.getDeviceModel().getSsid())
                .params(Config.USERNAME, userName)
                .params(Config.PASSWORD, password)
                .execute(new DialogCallback<LzyResponse<DeviceUser>>(this,view) {
                    @Override
                    public void onSuccess(Response<LzyResponse<DeviceUser>> response) {
                        int mStatus = response.body().status;
                        if (mStatus == Config.DEVICE_RESULT_ERROR_TIMEOUT){
                            T.showShort(getResources().getString(R.string.string_status_connect_timeout_error));
                        }else if (mStatus == Config.DEVICE_RESULT_EXCEPTIONS) {
                            T.showShort(getResources().getString(R.string.string_status_connect_httpservice_error));
                        }else if (mStatus == Config.DEVICE_RESULT_ERROR_SSID){
                            T.showShort(getResources().getString(R.string.string_status_connect_ssid_error));
                        }else if (mStatus == Config.DEVICE_RESULT_ERROR_PWD){
                            T.showShort(getResources().getString(R.string.string_status_connect_login_errer));
                        }else if (mStatus ==Config.DEVICE_RESULT_ERROR_LOGIN){
                            showConstraintLogin();
                        }else if (mStatus == Config.DEVICE_RESULT_SUCCESS ){
                            device.changeUser(userName,password);
                            device.setStatus(mStatus);
                            device.setSystemLevel(response.body().result.getType());
                            Intent intent = new Intent(DeviceEditActivity.this,DeviceInfoActivity.class);
                            intent.putExtra(Config.RESULT_CMS_SUCCESS,device.getDeviceModel().getSsid());
                            startActivity(intent);
                            finish();

                        }else {
                            T.showShort(getResources().getString(R.string.string_adddevice_error));
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<DeviceUser>> response) {
                        super.onError(response);
                        T.showShort(getResources().getString(R.string.string_adddevice_error));
                    }
                });
    }

    private void showConstraintLogin() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getResources().getString(R.string.string_hide));
        dialog.setMessage(getResources().getString(R.string.string_status_connect_haslogin_errer));
        dialog.setCancelable(false);
        dialog.setPositiveButton(getResources().getString(R.string.string_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                OkGo.<LzyResponse<DeviceUser>>post(Urls.URL_DEVICECONSTRAINTLOGIN)
                        .tag(DeviceEditActivity.this)
                        .params(Config.SSID, device.getDeviceModel().getSsid())
                        .params(Config.USERNAME, device.getDeviceModel().getUserName())
                        .execute(new DialogCallback<LzyResponse<DeviceUser>>(DeviceEditActivity.this) {
                            @Override
                            public void onSuccess(Response<LzyResponse<DeviceUser>> response) {
                                LzyResponse<DeviceUser> body = response.body();
                                if (body.status == Config.DEVICE_RESULT_SUCCESS){
                                    device.setStatus(body.status);
                                    device.setSystemLevel(body.result.getType());

                                    Intent intent = new Intent(DeviceEditActivity.this,DeviceInfoActivity.class);
                                    intent.putExtra(Config.SSID,device.getDeviceModel().getSsid());
                                    startActivity(intent);
                                    finish();
                                }
                            }

                            @Override
                            public void onError(Response<LzyResponse<DeviceUser>> response) {
                                super.onError(response);
                                T.showShort(getResources().getString(R.string.string_adddevice_error));
                            }
                        });

            }
        });
        dialog.setNegativeButton(getResources().getString(R.string.string_cancel),null);

        alertDialog = dialog.create();
        alertDialog.getWindow().setWindowAnimations(R.style.pickerview_dialogAnim);
        alertDialog.getWindow().setBackgroundDrawableResource(R.drawable.loading_bg);
        alertDialog.show();

    }

    private void showPwd() {
        isClickShowPwd = !isClickShowPwd;
        if (isClickShowPwd) {
            mShowPwdBtn.setText(getResources().getString(R.string.input_device_hidepwd));
            mEditPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }else {
            mShowPwdBtn.setText(getResources().getString(R.string.input_device_showpwd));
            mEditPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (alertDialog!=null){
            if (alertDialog.isShowing()){
                alertDialog.dismiss();
            }
            alertDialog = null;
        }
    }
}
